<?php
/**
 *
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-10-11
 * Time: 10:27
 */

namespace App\Http\Controllers\Api\V1\Front\Wallet;


use App\Http\Controllers\Controller;
use App\Libs\httpUtil;
use App\Libs\WXBizDataCrypt;
use App\Models\AreaTotal;
use App\Models\DeviceSetting;
use App\Models\Order;
use App\Models\User;
use App\Models\UserIncomeLog;
use App\Models\UserRelation;
use App\Models\UserWithdrawLog;
use App\Services\Front\AreaTotalService;
use App\Services\Front\IncomeService;
use App\Services\Wx\AliService;
use Illuminate\Http\Request;


class WalletController extends Controller
{
    public function walletShow(Request $request)
    {
        $user_id = $request->USERID;
        $user = User::select('id', 'user_id', 'headimgurl', 'isZFB', 'user_name', 'level', 'zfbName', 'zfbNumber', 'income', 'totalIncome', 'todayTaskNum', 'totalWithdraw', 'totalSaleNum')
            ->where('user_id', $user_id)->first();
        return $this->apiResponse($user);
    }

    public function upZFB(Request $request)
    {
        $user_id = $request->USERID;
        $zfbName = $request->zfbName;
        $zfbNumber = $request->zfbNumber;
        if (!$zfbName || !$zfbNumber) {
            return $this->apiResponse('', [
                'errorCode' => 30051,
                'errorMessage' => "支付宝信息不可为空"
            ]);
        }
        User::where('user_id', $user_id)->update(['zfbName' => $zfbName, 'zfbNumber' => $zfbNumber]);
        return $this->apiResponse(true);
    }


    public function getList(Request $request)
    {
        $user_id = $request->USERID;
        $pageSize = $request->pageSize;
        $listType = $request->listType;
        if ($listType == "INCOME") {
            $incomeLogList = UserIncomeLog::select('incomeLogId', 'price', 'source', 'createTime')
                ->where('user_id', $user_id)
                ->orderBy('createTime', 'desc')
                ->paginate($pageSize)->toArray();
            foreach ($incomeLogList['data'] as &$value) {
                $value['price'] = number_format($value['price'], 2);
            }
            $data['incomeLogList'] = $incomeLogList['data'];
            $data['totalNum'] = $incomeLogList['total'];
        } else {
            $withdrawLogList = UserWithdrawLog::select('userWithdrawLogId', 'withdrawPrice', 'surplusPrice', 'accountStatus', 'auditStatus', 'remark', 'createTime', 'accountTime')
                ->where('user_id', $user_id)
                ->orderBy('createTime', 'desc')
                ->paginate($pageSize)->toArray();
            foreach ($withdrawLogList['data'] as &$value) {
                $value['withdrawPrice'] = number_format($value['withdrawPrice'], 2);
                $value['surplusPrice'] = number_format($value['surplusPrice'], 2);
            }
            $data['withdrawLogList'] = $withdrawLogList['data'];
            $data['totalNum'] = $withdrawLogList['total'];
        }
        return $this->apiResponse($data);
    }

    public function withdraw(Request $request)
    {
        try {
            \DB::beginTransaction();
            $user_id = $request->USERID;
            $price = $request->price;
            if ($price <= 0) {
                return $this->apiResponse("", [
                    'errorCode' => '30002',
                    'errorMessage' => "非正常数值"
                ]);
            }
            $user = User::where('user_id', $user_id)->lockForUpdate()->first();
            if ($user) {
                if($user['integration'] < 100){
                    if($price < 0.1){
                        return $this->apiResponse('', [
                            'errorCode' => 30192,
                            'errorMessage' => "小于100积分，0.1元起提!"
                        ]);
                    }
                }else{
                    if($price < 1){
                        return $this->apiResponse('', [
                            'errorCode' => 30192,
                            'errorMessage' => "大于100积分,1元起提!"
                        ]);
                    }
                }
                if (!$user['zfbNumber']) {
                    return $this->apiResponse("", [
                        'errorCode' => '30002',
                        'errorMessage' => "未填写支付宝信息"
                    ]);
                }
                if ($user['integration'] >= 100) {
                    $order = Order::select('id')->where('user_id', $user_id)->whereIn('status', [1, 2, 3, 5, 8, 12])->first();
                    if (!$order) {
                        return $this->apiResponse("", [
                            'errorCode' => '30001',
                            'errorMessage' => "提现金额不足"
                        ]);
                    }
                }
                $float1 = intval(strval($user->totalIncome * 100)) - intval(strval($user->totalWithdraw * 100)) + intval(strval($user->totalSaleNum * 100));
                $float2 = intval(strval($price * 100));
                if (intval(strval($user->income * 100)) < $float2) {
                    return $this->apiResponse("", [
                        'errorCode' => '30001',
                        'errorMessage' => "提现金额不足"
                    ]);
                }
                if ($float1 < $float2) {
                    return $this->apiResponse("", [
                        'errorCode' => '30001',
                        'errorMessage' => "提现金额不足"
                    ]);
                }
                $surplusPrice = $user->income - $price;
                $time = date("Y-m-d H:i:s");
                $ip = getip();
                $userWithdrawLog = [];
                $userWithdrawLog['user_id'] = $user_id;
                $userWithdrawLog['withdrawPrice'] = $price;
                $userWithdrawLog['surplusPrice'] = $surplusPrice;
                $userWithdrawLog['createTime'] = $time;
                $userWithdrawLog['zfbName'] = $user->zfbName;
                $userWithdrawLog['zfbNumber'] = $user->zfbNumber;
                $userWithdrawLog['ip'] = $ip;
                UserWithdrawLog::insert($userWithdrawLog);
                User::where('user_id', $user_id)->update([
                    'income' => \DB::raw('income - ' . $price),
                    'totalWithdraw' => \DB::raw('totalWithdraw + ' . $price)
                ]);
            }
            \DB::commit();
            return $this->apiResponse(true);
        } catch (\Exception $e) {
            \DB::rollback();
            \Log::error("withdraw store:" . $e->getMessage());
            return $this->apiResponse('', config('errorCode.ADDRESS_UPDATE_FAILED'));
        }
    }

    public function incomeShow(Request $request)
    {
        $user_id = $request->USERID;
        $pageSize = $request->pageSize;
        $pageNo = $request->pageNo;
        $incomeLogId = $request->incomeLogId;
        $listType = $request->listType;
        $user = User::select('id', 'user_id', 'headimgurl', 'isZFB', 'user_name', 'level', 'zfbName', 'zfbNumber', 'income', 'totalIncome', 'todayTaskNum', 'totalWithdraw', 'totalSaleNum')->where('user_id', $user_id)->first();
        $incomeLog = UserIncomeLog::select('incomeLogId', 'price', 'invitePrice', 'indirectInvitePrice', 'incomeLogIdList', 'incomeLogPriceList', 'inviteNum', 'indirectInviteNum', 'rate')->where('incomeLogId', $incomeLogId)->where('user_id', $user_id)->first();
        $incomeLogIdList = explode(";", $incomeLog->incomeLogIdList);
        unset($incomeLogIdList[count($incomeLogIdList) - 1]);
        unset($incomeLogIdList[0]);
        $incomeLogIdList = array_values($incomeLogIdList);
        $incomeLogPriceList = explode(";", $incomeLog->incomeLogPriceList);
        unset($incomeLogPriceList[count($incomeLogPriceList) - 1]);
        unset($incomeLogPriceList[0]);
        $incomeLogPriceList = array_values($incomeLogPriceList);
        $sql = UserIncomeLog::select('t1.incomeLogId', 't1.price', 't1.createTime', 't2.user_id', 't2.headimgurl', 't2.user_name')
            ->from((new UserIncomeLog())->getTable() . ' as t1')
            ->join((new User())->getTable() . ' as t2', 't1.user_id', '=', 't2.user_id')
            ->join((new UserRelation())->getTable() . ' as t3', 't1.user_id', '=', 't3.userId');
        if($listType == "INDIRECT"){
            $sql->where('t3.inviteUserId','!=',$user_id);
        }else{
            $sql->where('t3.inviteUserId',$user_id);
        }
        $incomeLogList = $sql->whereIn('t1.incomeLogId', $incomeLogIdList)->paginate($pageSize)->toArray();
        $i = 0;
        foreach ($incomeLogList['data'] as &$value) {
            foreach ($incomeLogIdList as $key=>$val){
                if($value['incomeLogId'] == $val){
                    $value['price'] = number_format($incomeLogPriceList[$key], 2);
                    //$i = $i+$incomeLogPriceList[$key];
                    break;
                }
            }
        }
        unset($incomeLog->incomeLogIdList);
        unset($incomeLog->incomeLogPriceList);
        $incomeLog['invitePrice'] = number_format($incomeLog['invitePrice'], 2);
        $incomeLog['indirectInvitePrice'] = number_format($incomeLog['indirectInvitePrice'], 2);
        $incomeLog['incomeLogList'] = $incomeLogList['data'];
        $incomeLog['totalNum'] = $incomeLogList['total'];
        $user['incomeLog'] = $incomeLog;
        return $this->apiResponse($user);
    }
}